<template>
  <div class="math-test">
    <div v-if="currentStep === 'config'">
      <h2>数学测试配置</h2>
      <el-form :model="testConfig" label-width="120px">
        <el-form-item label="年级">
          <el-select v-model="testConfig.gradeId" placeholder="请选择年级" @change="loadKnowledgePoints">
            <el-option
              v-for="grade in grades"
              :key="grade.id"
              :label="grade.name"
              :value="grade.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="知识点">
          <el-select
            v-model="testConfig.knowledgePointIds"
            multiple
            placeholder="请选择知识点（可选）"
            :disabled="!testConfig.gradeId"
          >
            <el-option
              v-for="point in knowledgePoints"
              :key="point.id"
              :label="point.name"
              :value="point.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="题目数量">
          <el-input-number v-model="testConfig.questionCount" :min="5" :max="50" />
        </el-form-item>

        <el-form-item label="难度">
          <el-select v-model="testConfig.difficulty" placeholder="请选择难度（可选）">
            <el-option label="简单" :value="1" />
            <el-option label="中等" :value="2" />
            <el-option label="困难" :value="3" />
            <el-option label="挑战" :value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="题型">
          <el-checkbox-group v-model="testConfig.questionTypes">
            <el-checkbox label="choice">选择题</el-checkbox>
            <el-checkbox label="fill">填空题</el-checkbox>
            <el-checkbox label="solve">解答题</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="时间限制（分钟）">
          <el-input-number v-model="testConfig.timeLimit" :min="10" :max="120" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="generateTest" :loading="generating">
            生成试卷
          </el-button>
          <el-button @click="resetConfig">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div v-else-if="currentStep === 'test'">
      <TestPaper
        :test-paper="currentTestPaper"
        @submit="submitTest"
        @back="currentStep = 'config'"
      />
    </div>

    <div v-else-if="currentStep === 'result'">
      <TestResult
        :result="testResult"
        @retry="currentStep = 'config'"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import TestPaper from '@/components/TestPaper.vue'
import TestResult from '@/components/TestResult.vue'
import { mathTestApi } from '@/api/mathTest'

interface Grade {
  id: number
  name: string
  level: number
}

interface KnowledgePoint {
  id: number
  name: string
  description: string
  grade_id: number
}

interface TestConfig {
  gradeId: number | null
  knowledgePointIds: number[]
  questionCount: number
  difficulty: number | null
  questionTypes: string[]
  timeLimit: number | null
}

const currentStep = ref<'config' | 'test' | 'result'>('config')
const grades = ref<Grade[]>([])
const knowledgePoints = ref<KnowledgePoint[]>([])
const currentTestPaper = ref<any>(null)
const testResult = ref<any>(null)
const generating = ref(false)

const testConfig = reactive<TestConfig>({
  gradeId: null,
  knowledgePointIds: [],
  questionCount: 10,
  difficulty: null,
  questionTypes: ['choice', 'fill', 'solve'],
  timeLimit: null
})

onMounted(async () => {
  await loadGrades()
})

const loadGrades = async () => {
  try {
    console.log('正在加载年级数据...')
    const data = await mathTestApi.getGrades()
    console.log('年级数据加载成功:', data)
    grades.value = data
  } catch (error) {
    console.error('加载年级数据失败:', error)
    ElMessage.error('加载年级数据失败')
  }
}

const loadKnowledgePoints = async () => {
  if (!testConfig.gradeId) return
  
  try {
    knowledgePoints.value = await mathTestApi.getKnowledgePoints(testConfig.gradeId)
  } catch (error) {
    ElMessage.error('加载知识点数据失败')
  }
}

const generateTest = async () => {
  if (!testConfig.gradeId) {
    ElMessage.warning('请选择年级')
    return
  }

  generating.value = true
  try {
    currentTestPaper.value = await mathTestApi.generateTest({
      grade_id: testConfig.gradeId,
      knowledge_point_ids: testConfig.knowledgePointIds,
      difficulty: testConfig.difficulty,
      question_count: testConfig.questionCount,
      question_types: testConfig.questionTypes,
      time_limit: testConfig.timeLimit
    })
    
    currentStep.value = 'test'
    ElMessage.success('试卷生成成功！')
  } catch (error) {
    ElMessage.error('生成试卷失败')
  } finally {
    generating.value = false
  }
}

const submitTest = async (answers: any) => {
  try {
    const uid = localStorage.getItem('token') ? JSON.parse(atob(localStorage.getItem('token')!.split('.')[1] || 'e30='))?.sub : undefined
    testResult.value = await mathTestApi.submitTest(currentTestPaper.value.id, {
      answers: answers,
      user_id: uid
    })
    
    currentStep.value = 'result'
  } catch (error) {
    ElMessage.error('提交答案失败')
  }
}

const resetConfig = () => {
  testConfig.gradeId = null
  testConfig.knowledgePointIds = []
  testConfig.questionCount = 10
  testConfig.difficulty = null
  testConfig.questionTypes = ['choice', 'fill', 'solve']
  testConfig.timeLimit = null
  knowledgePoints.value = []
}
</script>

<style scoped>
.math-test {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.el-form {
  margin-top: 20px;
}

.el-select {
  width: 100%;
}
</style>